import os
import time
import subprocess
import sys
import auto_log
import auto_utility
from os.path import exists, join
PATH_ROOT = r'c:\Autotest_Files'
PATH_TO_LOGS = r'a:\py_logs.xml'
PATH_TO_DATA = r'e:\data'
PATH_TO_COUNT = join(PATH_ROOT,'count.ct')
def create_config(file_name, conf_id):
    try:
        file_conf = open(file_name, 'r')
        data = file_conf.read()
        file_conf.close()
    except:
        auto_log.write_result(PATH_TO_LOGS, file_name, auto_log.STATUS_ERROR, "can't open th file")
        return -1
    for conf in data.split('<createConfig>')[1:]:
        operations = conf.split('</createConfig>')[0].split('<operation>')
        id = operations[0].split('<id>')[1].split('</id>')[0]
        if id == conf_id:
            print(id)
            for op in operations[1:]:
                name_op = op.split('<name>')[1].split('</name>')[0]
                execute_op = op.split('<execute>')[1].split('</execute>')[0].split('\n')[1:-1]
                if name_op == 'diskpart':
                    print(execute_op)
                    result = auto_utility.call_diskpart(execute_op)
                    if result != 0:
                        auto_log.write_result(PATH_TO_LOGS, result, auto_log.STATUS_ERROR, "create_config ok conf = " + id)
                        return -1
                    else:
                        auto_log.write_result(PATH_TO_LOGS, 'diskpart operation', auto_log.STATUS_OK, "create_config ok conf = " + id)
                elif name_op == 'format':
                    for command in execute_op:
                        print(command)
                        result = get_cmd_output(command)['err']
                        if result !=0:
                            auto_log.write_result(PATH_TO_LOGS, command, auto_log.STATUS_ERROR, "create_config ok conf = " + id)
                            return -1
                        else:
                            auto_log.write_result(PATH_TO_LOGS, command, auto_log.STATUS_OK, "create_config ok conf = " + id)
    return 0

def parse_data_data():
    PATH_DATA = join(PATH_ROOT,'data.data')
    if not exists(PATH_DATA):
        auto_log.write_result(PATH_TO_LOGS, PATH_DATA, auto_log.STATUS_ERROR, "parse_data_data")
        return -1
    try:
        file = open(PATH_DATA, "r")
        data = file.read()
        file.close()
    except:
        print("Can't parse data.data")
        return -1
    for tmp in data.split('<file>'):
        if tmp:
            file = tmp.split('</file>')[0]
            name = file.split('<name>')[1].split('</name>')[0]
            PATH_FILE = PATH_ROOT
            content = file.split('<content>')[1].split('</content>')[0]
            try:
                to_write = open(join(PATH_FILE,name),'w')
                to_write.write(content)
                to_write.close()
            except:
                print("Can't write to " + join(PATH_FILE,name))
                return -1
    return 0
def parse_task_name():
    task = auto_utility.file_from_path(PATH_ROOT, '.psl')['res']
    name = task.split('\\')[-1][3:-4]
    if name != '':
        return name
    else:    
        return -1
def get_cmd_output(cmd_command):
    #--------------------------------------------------
    path_name = "get_cmd_output_" + str(time.time()) + ".txt"
    command = cmd_command + " > " + path_name
    error = os.system(command)
    #--------------------------------------------------
    file = open(path_name, "r")
    data = file.read()
    file.close()
    #--------------------------------------------------
    stop = 0
    while stop != 1:
        try:
            os.remove(path_name)
            stop = 1
        except:
            time.sleep(5)
    #--------------------------------------------------
    result = {"err": error, "out": data}
    return result

def get_cmd_output2(cmd_command, encoding=sys.stdout.encoding):
    p = subprocess.Popen(cmd_command, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
    out, err = p.communicate()
    out = out.decode(encoding)
    out = out.replace("\r\n", "\n")
    out = out.replace("\r", "\n")
    result = {"err": p.returncode, "out": out}
    return result

def fg_generate_by_size(PATH_FG, PATH_FILES, mask, all_size, min_size, max_size):
    if not PATH_FG:
        PATH_FG_xp32 = r'"C:\Documents and Settings\user\Desktop\FG 3.01.029.exe"'
        PATH_FG_all = r'"C:\Users\Administrator\Desktop\FG 3.01.029.exe"'
        if exists(r"C:\Documents and Settings\user\Desktop\FG 3.01.029.exe"):
            PATH_FG = PATH_FG_xp32
        elif exists(r"C:\Users\Administrator\Desktop\FG 3.01.029.exe"):
            PATH_FG = PATH_FG_all
    command = PATH_FG + " /s /allsize:" + all_size + " /root:" + PATH_FILES + \
    " /minsize:" + min_size + " /maxsize:" + max_size + " /filemask:" + mask
    cmd = get_cmd_output(command)
    return cmd["err"]

def file_create(file_name):
    try:
        file = open(join(PATH_ROOT,file_name), 'w')
        file.write(" ")
        file.close()
    except:
        auto_log.write_result(PATH_TO_LOGS, file_name, auto_log.STATUS_ERROR, "can't create file")
        return -1
    return 0

def file_delete(file_name):
    try:
        os.remove(join(PATH_ROOT,file_name))
    except:
        auto_log.write_result(PATH_TO_LOGS, file_name, auto_log.STATUS_ERROR, "can't delete file")
        return -1
    return 0

def fsum_create_md5(fsum, path):
    if not fsum:
        fsum_x32 = r"C:\Program Files\FastSum\fsum.exe"
        fsum_x64 = r"C:\Program Files (x86)\FastSum\fsum.exe"
        if exists(fsum_x32):
            fsum = fsum_x32
        elif exists(fsum_x64):
            fsum = fsum_x64
    auto_log.write_result(PATH_TO_LOGS, fsum, auto_log.STATUS_OK, "fsum_create_md5")
    fsum = '"%s"' % (fsum)
    param = " /T:F /R /O"
    command = fsum + " " + path + param
    cmd_result = get_cmd_output(command)
    return cmd_result['err']

def fsum_check_md5(fsum, path):
    if not fsum:
        fsum_x32 = r"C:\Program Files\FastSum\fsum.exe"
        fsum_x64 = r"C:\Program Files (x86)\FastSum\fsum.exe"
        if exists(fsum_x32):
            fsum = fsum_x32
        elif exists(fsum_x64):
            fsum = fsum_x64
    auto_log.write_result(PATH_TO_LOGS, fsum, auto_log.STATUS_OK, "fsum_check_md5")
    fsum = '"%s"' % (fsum)
    param = " /T:F /R /V"
    command = fsum + " " + path + param
    cmd_result = get_cmd_output(command)
    return cmd_result

def change_dest_in_txt():
    name = ''
    for item in os.listdir(PATH_ROOT):
        if os.path.isfile(join(PATH_ROOT, item)):
            name = item.split('\\')[-1]
            if name.find('rf_') != -1 and name.endswith('fr1.txt'):
                fr_file = name
    if not name:
        auto_log.write_result(PATH_TO_LOGS, "cant find name, what need change", auto_log.STATUS_ERROR, "change_dest_in_txt")
        return -1
    try:
        file = open(join(PATH_ROOT ,str(fr_file)),'r')
        data = file.read()
        file.close()
    except:
        auto_log.write_result(PATH_TO_LOGS, join(PATH_ROOT ,str(fr_file)), auto_log.STATUS_ERROR, "change_dest_in_txt")
        return -1

    tmp = data.split('FB_PROPERTY_ARCHIVE_PATH=')[1].split('FB_PROPERTY_MAX_LOG_RECORDS')[0]
    el = tmp.split('/')
    if len(el) == 1:
        el = tmp.split('\\')
    name_old = el[2]
    path_to_arc = el[0] + '\\' + el[1]
    for item in os.listdir(path_to_arc):
        if os.path.isdir(path_to_arc + '\\' + item) and item != 'FL000000000000000000':
            name_new = item       
    data = data.replace(name_old,name_new)
    try:
        file = open(join(PATH_ROOT, str(fr_file)),'w')
        file.write(data)
        file.close()
    except:
        auto_log.write_result(PATH_TO_LOGS, join(PATH_ROOT, str(fr_file)), auto_log.STATUS_ERROR, "change_dest_in_txt")
        return -1
    return 0

def change_dest_in_txt_for_UFSD():
    name = ''
    for item in os.listdir(PATH_ROOT):
        if os.path.isfile(join(PATH_ROOT ,item)):
            name = item.split('\\')[-1]
            if name.find('rf_') != -1 and name.endswith('fr1.txt'):
                fr_file = name
    if not name:
        auto_log.write_result(PATH_TO_LOGS, "cant find name, what need change", auto_log.STATUS_ERROR, "change_dest_in_txt_for_UFSD")
        return -1
    try:
        file = open(join(PATH_ROOT, str(fr_file)),'r')
        data = file.read()
        file.close()
    except:
        auto_log.write_result(PATH_TO_LOGS, join(PATH_ROOT ,str(fr_file)), auto_log.STATUS_ERROR, "change_dest_in_txt_for_UFSD")
        return -1

    tmp = data.split('FB_PROPERTY_ARCHIVE_PATH=')[1].split('FB_PROPERTY_MAX_LOG_RECORDS')[0]
    el = tmp.split('/')
    if len(el) == 1:
        el = tmp.split('\\')
    name_old = el[4]
    path_to_arc = 'I:' + '\\' + el[3]
    for item in os.listdir(path_to_arc):
        if os.path.isdir(path_to_arc + '\\' + item) and item != 'FL000000000000000000':
            name_new = item       
    data = data.replace(name_old,name_new)
    try:
        file = open(join(PATH_ROOT, str(fr_file)),'w')
        file.write(data)
        file.close()
    except:
        auto_log.write_result(PATH_TO_LOGS, join(PATH_ROOT, str(fr_file)), auto_log.STATUS_ERROR, "change_dest_in_txt_for_UFSD")
        return -1
    return 0
def get_count():
    try:
        file = open(PATH_TO_COUNT, 'r')
        count = file.readline()
        file.close()
    except:
        auto_log.write_result(PATH_TO_LOGS, 'cant get count', auto_log.STATUS_ERROR, "get_count")
        print('error')
        return -1
    return count
def set_count(count):
    try:
        file = open(PATH_TO_COUNT, 'w')
        file.write(count)
        file.close()
    except:
        auto_log.write_result(PATH_TO_LOGS, 'cant set count = ' + count, auto_log.STATUS_ERROR, "set_count")
        return -1
    return 0
def inc_count():
    i = int(get_count())
    i = i + 1
    set_count(str(i))
    return 0
